package com.yanxml.core.java.reference;

import com.yanxml.core.java.reference.soft_reference.SoftReferenceTest_OOM;
import org.junit.Assert;
import org.junit.Test;

import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * 用于测试和模拟. 强/弱/软/虚 4种引用类型.
 *
 * @author sean
 * @date 2024/06/08
 */
public class ReferenceTest {

    @Test
    public void testStrongReference() {
        // init data
        Integer testNumber = new Integer(1);

        // do case
        System.gc();

        // assert
        Assert.assertNotNull(testNumber);
        Assert.assertTrue(testNumber.intValue() == 1);
    }

    @Test
    public void testSoftReference() {
        // init data
        SoftReference<List<String>> testNumberRef = new SoftReference<List<String>>(new ArrayList<>(100*100*100));

        // do case
        // max max size object

        System.gc();

        // assert
        Assert.assertNotNull(testNumberRef);
        Assert.assertNotNull(testNumberRef.get());
    }

    @Test
    public void testWeakReference() {
        // init data
        WeakReference<Integer> testNumberRef = new WeakReference<Integer>(new Integer(1));

        // do case
        System.gc();

        // assert
        Assert.assertTrue(null == testNumberRef.get());
    }

    @Test
    public void testWeakReference2() {
        // init data
        Integer testNumber = new Integer(1);
        WeakReference<Integer> testNumberRef = new WeakReference<Integer>(testNumber);

        // do case
        System.gc();

        // assert
        Assert.assertNotNull(testNumberRef.get());
    }


}
